<template>
  <div class="pod">
    <el-row>
      <!-- 头部1 -->
      <el-col :span="24">
        <div>
          <el-card class="pod-head-card" shadow="never" :body-style="{padding:  '10px'}">
            <el-row>
              <!-- 命名空间 -->
              <el-col :span="6">
                <div style="display: table-row">
                  <span>命名空间 : </span>
                  <el-select v-model="namespaceValue" filterable placeholder="请选择">
                    <el-option
                    v-for="(item,index) in namespaceList"
                    :key="index"
                    :label="item.metadata.name"
                    :value="item.metadata.name">
                    </el-option>
                  </el-select>
                </div>   
              </el-col>
              <!-- deploy名称,叫做app -->
              <el-col :span="6">
                <div style="display: table-row">
                  <span>App : </span>
                  <el-select v-model="namespaceAppValue" filterable placeholder="请选择">
                    <el-option
                    v-for="(item,index) in namespaceAppList"
                    :key="index"
                    :label="item.metadata.name"
                    :value="item.metadata.name">
                    </el-option>
                  </el-select>
                </div>
              </el-col>
              <!-- 刷新按钮 -->
              <el-col :span="2" :offset="10">
                <div>
                  <el-button style="botder-radius:2px" icon="Refresh" plain @click="getPods()">刷新</el-button>
                </div>
              </el-col>
            </el-row>
          </el-card>
        </div>
      </el-col>
      <!-- 头部2 -->
      <el-col :span="24">
        <div>
          <el-card class="pod-head-card" shadow="never" :body-style="{padding:'10px'}">
            <el-row>
              <!-- 创建按钮 -->
              <el-col :span="2" >
                <div>
                  <el-button disabled style="border-radius: 2px;"
                  icon="Edit"
                  type="primary"> 创建
                  </el-button>
                </div>
              </el-col>
              <!-- 搜索框和搜索按钮 -->
              <el-col :span="6">
                <div>
                  <el-input class="pod-head-search"
                  clearable placeholder="请输入"
                  v-model="searchInput"></el-input>
                  <el-button style="border-radius:2px;"
                  icon="Search" type="primary" plain @click="getPods()"></el-button>
                </div>

              </el-col>
            </el-row>
          </el-card>
        </div>
      </el-col>
      <!-- 数据表格 -->
      <el-col :span="24">
      <div>
        <el-card class="pod-body-card" shadow="never" :body-style="{padding: '5px'}">
          <el-table style="width: 100%;font-size:12px;margin-bottom:10px" :data="podnameList">
              <el-table-column width="10"></el-table-column>
              <el-table-column align="left"  min-width="200" label="Pod名">
                  <template v-slot="scope">
                    <a class="pod-body-podname">{{ scope.row.metadata.name }}</a>
                  </template>
              </el-table-column>
              <el-table-column align=center min-width="150" label="IP">
                  <template v-slot="scope">
                      <el-tag v-if="scope.row.status.podIP !== undefined" type="info">{{ scope.row.status.podIP }}</el-tag>
                  </template>
              </el-table-column>
              <el-table-column align=center min-width="100" label="节点">
                  <template v-slot="scope">
                      <el-tag v-if="scope.row.spec.nodeName !== undefined" type="warning">{{ scope.row.spec.nodeName }}</el-tag>
                  </template>
              </el-table-column>
              <el-table-column align=center label="状态">
                  <template v-slot="scope">
                      <div :class="{'success-dot':scope.row.status.phase == 'Running', 'warning-dot':scope.row.status.phase == 'Pending', 'error-dot':scope.row.status.phase != 'Running' && scope.row.status.phase != 'Pending'}"></div>
                      <span :class="{'success-status':scope.row.status.phase == 'Running', 'warning-status':scope.row.status.phase == 'Pending', 'error-status':scope.row.status.phase != 'Running' && scope.row.status.phase != 'Pending'}">{{ scope.row.status.phase }} </span>
                  </template>
              </el-table-column>
              <el-table-column align=center label="重启次数">
                  <template v-slot="scope">
                      <span>{{ restartTotal(scope) }} </span>
                  </template>
              </el-table-column>
              <el-table-column align=center min-width="110" label="创建时间">
                  <template v-slot="scope">
                      <el-tag type="info">{{ timeTrans(scope.row.metadata.creationTimestamp) }} </el-tag>
                  </template>
              </el-table-column>
               
              
              <!-- 操作列，放按钮 -->
              <el-table-column align=center label="操作" width="200">
                  <template v-slot="scope">
                      <el-button size="small" style="border-radius:2px;" icon="Edit" type="primary" plain @click="getPodDetail(scope)">YAML</el-button>
                      <el-button size="small" style="border-radius:2px;" icon="Delete" type="danger" @click="handleConfirm(scope, '删除', delPod)">删除</el-button>
                  </template>
              </el-table-column>
          </el-table>
          <!-- size-change 单页大小改变后触发
          current-change 页数改变后触发
          current-page 当前页，跟后端page一致
          page-size 单页大小，跟后端limit一致 -->
          <el-pagination
            class="pod-body-pagination"
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="pagesizeList"
            :page-size="pagesize"
            layout="total,sizes,prev,pager,next,jumper"
            :total="podnameTotal"></el-pagination>
        </el-card>
      </div>

      </el-col>
    </el-row>

    <!-- YAML -->
    <el-dialog title="YAML信息" v-model="yamlDialog" width="60%" top="2%">
      <codemirror
          :value="contentYaml"
          border
          :options="cmOptions"
          height="500"
          style="font-size: 14px;"
          @change="onChange">
      </codemirror>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="yamlDialog = false">取消</el-button>
          <!-- <el-button type="primary" @click="updatePod()">更新</el-button> -->
        </span>
      </template>
    </el-dialog>

  </div>
  
</template>

<script>
import common from "../common/Config";
import httpClient from "../../utils/request";
import yaml2obj from 'js-yaml';
import json2yaml from "json2yaml";

export default {
  data() {
    return {
      //搜索
      searchInput: '',
      // 命名空间属性
      namespaceValue: 'default',
      namespaceList:  [],
      namespaceListUrl: common.k8sNamespaceList,

      // Deployment属性
      namespaceAppValue: '',
      namespaceAppList: [],
      namespaceAppListUrl: common.k8sDeploymentList,

      // 列表
      apploading: false,
      podnameList: [],
      podnameTotal: 0,
      getPodData: {
          url: common.k8sPodList,
          params: {
            filter_name: '',
            namespace: '',
            deploymentname: '',
            page: 1,
            limit: 10
          }
      },
      //分页
      currentPage: 1,
      pagesize: 10,
      pagesizeList: [10,20,30],
      // 编辑器配置
      cmOptions: common.cmOptions,
      contentYaml: '',
      // 列表
      deploymentList: [],
      deploymentTotal: 0,
      getDeploymentData: {
          url: common.k8sDeploymentList,
          params: {
            filter_name: '',
            namespace: '',
            page: 1,
            limit: 100
          }
      },
      // created() {
      //   //如果使用query方式传入的参数使用this.$route.query 接收
      //   //如果使用params方式传入的参数使用this.$router.params接收
      //     var param = this.$route.params;
      //     if (param.app) {
      //     console.log(param.app)
      //     } 
      // },

      // 详 情
      yamlDialog: false,
      podnameDetail: {},
      getpodnameDetailData: {
        url: common.k8sPodDetail,
        params: {
          podname: '',
          namespace: ''
        }
      },
      // 更新
      updatePodData: {
        url: common.k8sPodUpdate,
        params: {
          content: '',
          namespace: ''
        }
      },
       
      //删除
      delDialog: false,
      delPodData: {
          url: common.k8sPodDel,
          params: {
              podname: '',
              namespace: '',
          }
      },
    }
  },
  methods: {
    
    //json to yaml 
    transYaml(content) {
      return json2yaml.stringify(content)
    },
    transObj(content) {
      return yaml2obj.load(content)
    },
    // 编辑器内容发生变化时触发的方法
    onChange(val) {
      this.contentYaml = val
    },
    //分页
    handleSizeChange(size) {
      this.pagesize = size
      this.getPods()
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
      this.getPods()
    },
    //格林威治时间转为北京时间
    timeTrans(timestamp) {
        let date = new Date(new Date(timestamp).getTime() + 8 * 3600 * 1000)
        date = date.toJSON();
        date = date.substring(0, 19).replace('T', ' ')
        return date 
    },
    //字符串的截取
    ellipsis(value) {
      return value.length>15?value.substring(0,15)+'...':value
    },
    // 处理抽屉的关闭，double check，增加体验
    handleClose(done){
      this.$confirm('确认关闭')
      .then(()=> {
        done();
      })
      .catch(()=>{})
    },
    getNamespacesList() {
      httpClient.get(this.namespaceListUrl)
      .then(res => {
        this.namespaceList = res.data.items
      })
      .catch(res => {
        this.$message.error({
          message: res.msg
        })
      })
      this.getNamespaceAppsList()
    },
    getNamespaceAppsList() {
      this.apploading = true
      this.getDeploymentData.params.filter_name = ''
      this.getDeploymentData.params.namespace =this.namespaceValue
      this.getDeploymentData.params.page = 1
      this.getDeploymentData.params.limit = 100

      httpClient.get(this.namespaceAppListUrl,{params: this.getDeploymentData.params})
      .then(res => {
        this.namespaceAppList = res.data.items
      })
      .catch(res => {
        this.$message.error({
          message: res.msg
        })
      })
      this.getPods()
    },
    // 获取podname 列表
    getPods(){
      this.apploading = true
      this.getPodData.params.filter_name = this.searchInput
      this.getPodData.params.namespace = this.namespaceValue
      this.getPodData.params.deploymentname = this.namespaceAppValue
      this.getPodData.params.page = this.currentPage
      this.getPodData.params.limit = this.pagesize
      httpClient.get(this.getPodData.url,{params: this.getPodData.params})
      .then(res => {
        this.podnameList = res.data.items
        this.podnameTotal = res.data.total
      })
      .catch(res => {
        this.$message.error({
          message: res.msg
        })
      })
      this.apploading = false
    },
    // 获取详情, e参数标识传入的scope插槽，.row是该行的数据
    getPodDetail(e) {
      this.getpodnameDetailData.params.podname = e.row.metadata.name
      // 由于我写的后端传参名字是podname
      // this.PodDetailData.params.podname_name = e.row.metadata.name
      this.getpodnameDetailData.params.namespace = this.namespaceValue
      httpClient.get(this.getpodnameDetailData.url,{params: this.getpodnameDetailData.params})
      .then(res => {
        this.podnameDetail = res.data
        this.contentYaml = this.transYaml(this.podnameDetail)
        this.yamlDialog = true
      })
      .catch(res => {
        this.$message.error({
          message: res.msg
        })
      })
    },
   
    // 更新，删除
    //弹出确认框，用于危险操作的double check
    //obj是行数据（scope相当于一行的数据， scope.row相当于当前行的数据对象），opeateName是操作名，fn是操作的方法
    handleConfirm(obj,operateName,fn) {
    // handleConfirm( operateName) {
        this.confirmContent = '确认继续 ' + operateName + ' 操作吗？'
        //$confirm用于弹出确认框
        this.$confirm(this.confirmContent,'提示',{
            confirmButtonText: '确定',
            cancelButtonText: '取消',
        })
        .then(() => {
          // 需要传入obj，否则下面无法拿到数据
          fn(obj)
          // 如果没有传入fn，可以使用下面这种方法
          // this.restartPod(obj)
        })
        .catch(() => {
            this.$message.info({
                message: '已取消操作'
            })          
        })
    },
    //删除方法
    delPod(obj){
      this.delPodData.params.podname = obj.row.metadata.name
      this.delPodData.params.namespace = this.namespaceValue
      httpClient.delete(this.delPodData.url,{data: this.delPodData.params})
      .then(res => {
          this.$message.success({
          message: res.msg
          })
      })
      .catch(res => {
          this.$message.error({
          message: res.msg
          })
      })
      // //关闭弹出框
      // this.delDialog = false
      //更新后重新获取列表
  
      this.getPods()
    },
    restartTotal(e) {
        let index, sum = 0
        let containerStatuses = e.row.status.containerStatuses
        for ( index in containerStatuses) {
            sum = sum + containerStatuses[index].restartCount 
        }
        return sum
    },
    
  },
  watch: {
    namespaceValue: {
      handler(){
        localStorage.setItem('namespace',this.namespaceValue)
        this.currentPage = 1
      //  this.namespaceAppValue = ''
        this.getNamespaceAppsList()
        // 不允许直接获取ns下所有的pod，必须添加附加值deployment
        //this.getPods()
      }
    },
    namespaceAppValue: {
      handler(){
        localStorage.setItem('namespaceApp',this.namespaceAppValue)
        this.currentPage = 1
        this.getNamespaceAppsList()
        this.getPods()
      }
    },
  },
  beforeMount(){
    if(localStorage.getItem('namespace') !== undefined && localStorage.getItem('namespace') !== null){
      this.namespaceValue = localStorage.getItem('namespace')
    }
    if(localStorage.getItem('namespaceApp') !== undefined && localStorage.getItem('namespaceApp') !== null){
      this.namespaceAppValue = localStorage.getItem('namespaceApp')
    }
   
    this.getNamespacesList()
    this.getNamespaceAppsList()
    this.getPods()
  }
}

</script>

<style scoped>
  .pod-head-card,.pod-body-card {
        border-radius: 1px;
        margin-bottom: 5px;
    }
    .pod-head-search {
        width:160px;
        margin-right:10px; 
    }
    .pod-body-podname {
        color: #4795EE;
    }
    .pod-body-podname:hover {
        color: rgb(84, 138, 238);
        cursor: pointer;
        font-weight: bold;
    }
    .success-dot{
        display:inline-block;
        width: 7px;
        height:7px;
        background: rgb(27, 202, 21);
        border-radius:50%;
        border:1px solid rgb(27, 202, 21);
        margin-right: 10px;
    }
    .warning-dot{
        display:inline-block;
        width: 7px;
        height:7px;
        background: rgb(233, 200, 16);
        border-radius:50%;
        border:1px solid rgb(233, 200, 16);
        margin-right: 10px;
    }
    .error-dot{
        display:inline-block;
        width: 7px;
        height:7px;
        background: rgb(226, 23, 23);
        border-radius:50%;
        border:1px solid rgb(226, 23, 23);
        margin-right: 10px;
    }
    .success-status {
        color: rgb(27, 202, 21);
    }
    .warning-status {
        color: rgb(233, 200, 16);
    }
    .error-status {
        color: rgb(226, 23, 23);
    }
    .el-tabs__item {
        font-size: 12px;
    }
    .el-tabs__header {
        margin-bottom: 8px;
    }
    .pod-body-log-card, .pod-body-shell-card {
        border-radius:1px;
        height:600px;
        overflow:auto;
        background-color: #060101;
    }
    .pod-body-log-card {
        color: aliceblue;
    }
    .pod-body-log-span {
        white-space:pre;
    }
</style>